import React, { useCallback, useState } from 'react';
import {
  Box,
  Typography,
  Paper,
  Button,
  Grid,
  Card,
  CardMedia,
  IconButton,
  Chip,
  Alert,
} from '@mui/material';
import {
  CloudUpload,
  Delete,
  Image as ImageIcon,
  VideoFile,
} from '@mui/icons-material';
import { ContentType } from '../../../types';

interface MediaUploaderProps {
  contentType: ContentType;
  cover?: File;
  images?: File[];
  video?: File;
  onChange: (data: {
    cover?: File;
    images?: File[];
    video?: File;
  }) => void;
}

const MediaUploader: React.FC<MediaUploaderProps> = ({
  contentType,
  cover,
  images = [],
  video,
  onChange,
}) => {
  const [dragOver, setDragOver] = useState(false);

  // 处理封面上传
  const handleCoverUpload = useCallback((file: File) => {
    if (file.type.startsWith('image/')) {
      onChange({ cover: file });
    } else {
      alert('封面只能上传图片文件');
    }
  }, [onChange]);

  // 处理图片上传
  const handleImagesUpload = useCallback((files: FileList) => {
    const imageFiles = Array.from(files).filter(file => file.type.startsWith('image/'));
    const newImages = [...images, ...imageFiles].slice(0, 8); // 最多8张
    onChange({ images: newImages });
  }, [images, onChange]);

  // 处理视频上传
  const handleVideoUpload = useCallback((file: File) => {
    if (file.type.startsWith('video/')) {
      onChange({ video: file });
    } else {
      alert('请上传视频文件');
    }
  }, [onChange]);

  // 删除图片
  const handleDeleteImage = useCallback((index: number) => {
    const newImages = images.filter((_, i) => i !== index);
    onChange({ images: newImages });
  }, [images, onChange]);

  // 文件拖拽处理
  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setDragOver(true);
  }, []);

  const handleDragLeave = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setDragOver(false);
  }, []);

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setDragOver(false);
    
    const files = e.dataTransfer.files;
    if (files.length > 0) {
      if (contentType === ContentType.IMAGE) {
        handleImagesUpload(files);
      } else {
        handleVideoUpload(files[0]);
      }
    }
  }, [contentType, handleImagesUpload, handleVideoUpload]);

  // 格式化文件大小
  const formatFileSize = (bytes: number) => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  return (
    <Box>
      <Typography variant="h6" gutterBottom sx={{ mb: 3, textAlign: 'center' }}>
        上传媒体文件
      </Typography>

      {/* 封面上传区域 */}
      <Paper elevation={1} sx={{ p: 3, mb: 3 }}>
        <Typography variant="subtitle1" gutterBottom>
          封面图片 (可选)
        </Typography>
        
        {cover ? (
          <Box sx={{ position: 'relative', display: 'inline-block' }}>
            <img
              src={URL.createObjectURL(cover)}
              alt="封面预览"
              style={{
                width: '200px',
                height: '150px',
                objectFit: 'cover',
                borderRadius: '8px',
              }}
            />
            <IconButton
              size="small"
              sx={{
                position: 'absolute',
                top: -8,
                right: -8,
                bgcolor: 'error.main',
                color: 'white',
                '&:hover': { bgcolor: 'error.dark' },
              }}
              onClick={() => onChange({ cover: undefined })}
            >
              <Delete fontSize="small" />
            </IconButton>
          </Box>
        ) : (
          <Button
            variant="outlined"
            component="label"
            startIcon={<ImageIcon />}
            sx={{ mr: 2 }}
          >
            选择封面
            <input
              type="file"
              hidden
              accept="image/*"
              onChange={(e) => e.target.files?.[0] && handleCoverUpload(e.target.files[0])}
            />
          </Button>
        )}
      </Paper>

      {/* 主要内容上传区域 */}
      <Paper 
        elevation={1} 
        sx={{ 
          p: 3,
          border: dragOver ? '2px dashed #2196f3' : '2px dashed #ddd',
          backgroundColor: dragOver ? 'rgba(33, 150, 243, 0.05)' : 'transparent',
          transition: 'all 0.3s ease',
        }}
        onDragOver={handleDragOver}
        onDragLeave={handleDragLeave}
        onDrop={handleDrop}
      >
        {contentType === ContentType.IMAGE ? (
          <>
            <Typography variant="subtitle1" gutterBottom>
              图片文件 (必填，最多8张)
            </Typography>
            
            {images.length > 0 ? (
              <Grid container spacing={2} sx={{ mb: 2 }}>
                {images.map((image, index) => (
                  <Grid size={{ xs: 6, sm: 4, md: 3 }} key={index}>
                    <Card sx={{ position: 'relative' }}>
                      <CardMedia
                        component="img"
                        height="120"
                        image={URL.createObjectURL(image)}
                        alt={`图片 ${index + 1}`}
                        sx={{ objectFit: 'cover' }}
                      />
                      <IconButton
                        size="small"
                        sx={{
                          position: 'absolute',
                          top: 4,
                          right: 4,
                          bgcolor: 'rgba(0,0,0,0.5)',
                          color: 'white',
                          '&:hover': { bgcolor: 'rgba(0,0,0,0.7)' },
                        }}
                        onClick={() => handleDeleteImage(index)}
                      >
                        <Delete fontSize="small" />
                      </IconButton>
                      <Chip
                        label={formatFileSize(image.size)}
                        size="small"
                        sx={{
                          position: 'absolute',
                          bottom: 4,
                          left: 4,
                          bgcolor: 'rgba(0,0,0,0.7)',
                          color: 'white',
                        }}
                      />
                    </Card>
                  </Grid>
                ))}
              </Grid>
            ) : null}

            {images.length < 8 && (
              <Button
                variant="outlined"
                component="label"
                startIcon={<CloudUpload />}
                size="large"
                fullWidth
                sx={{ py: 2 }}
              >
                点击选择图片或拖拽到此处
                <input
                  type="file"
                  hidden
                  multiple
                  accept="image/*"
                  onChange={(e) => e.target.files && handleImagesUpload(e.target.files)}
                />
              </Button>
            )}

            {images.length >= 8 && (
              <Alert severity="info">
                已达到最大上传数量限制（8张图片）
              </Alert>
            )}
          </>
        ) : (
          <>
            <Typography variant="subtitle1" gutterBottom>
              视频文件 (必填)
            </Typography>
            
            {video ? (
              <Box sx={{ position: 'relative', display: 'inline-block', width: '100%' }}>
                <video
                  src={URL.createObjectURL(video)}
                  controls
                  style={{
                    width: '100%',
                    maxWidth: '400px',
                    height: '300px',
                    objectFit: 'cover',
                    borderRadius: '8px',
                  }}
                />
                <Box sx={{ mt: 2, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <Typography variant="body2" color="text.secondary">
                    {video.name} ({formatFileSize(video.size)})
                  </Typography>
                  <Button
                    variant="outlined"
                    color="error"
                    startIcon={<Delete />}
                    onClick={() => onChange({ video: undefined })}
                  >
                    删除
                  </Button>
                </Box>
              </Box>
            ) : (
              <Button
                variant="outlined"
                component="label"
                startIcon={<VideoFile />}
                size="large"
                fullWidth
                sx={{ py: 3 }}
              >
                点击选择视频或拖拽到此处
                <input
                  type="file"
                  hidden
                  accept="video/*"
                  onChange={(e) => e.target.files?.[0] && handleVideoUpload(e.target.files[0])}
                />
              </Button>
            )}
          </>
        )}
      </Paper>

      {/* 提示信息 */}
      <Box sx={{ mt: 3 }}>
        <Typography variant="body2" color="text.secondary" sx={{ textAlign: 'center' }}>
          {contentType === ContentType.IMAGE 
            ? '💡 支持JPG、PNG格式，单张图片不超过10MB'
            : '💡 支持MP4、AVI、MOV格式，视频文件不超过100MB'
          }
        </Typography>
      </Box>
    </Box>
  );
};

export default MediaUploader; 